﻿ 
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using WQDSkin.Forms.Component;

namespace WQDSkin.Forms.Component
{
    public class BasePage : Page
    {
        public WQDEditPage Contain;
        protected PageDoType doType;

        public BasePage()
        {
            
        }

        /// <summary>
        /// 窗口回调用
        /// </summary>
        /// <param name="model"></param>
        public virtual void CallBack(object model)
        {
            
        }

        /// <summary>
        /// 点取消时，反回主页面,主页面重新加载数据
        /// </summary>
        /// <param name="model"></param>
        public void GoBack(object model)
        {
            this.Contain.CallBack(model);
        }

        /// <summary>
        /// 导航到编辑窗口
        /// </summary>
        /// <param name="uriString"></param>
        /// <param name="data"></param>
        protected void Navigate(string uriString, object data)
        {
            this.Contain.Navigate(uriString, data);
        }

        /// <summary>
        /// 没有任何操作的取消,主页面不重新加载数据
        /// </summary>
        public void Cancel()
        {
            if (this.Contain != null)
            {
                this.Contain.GoBack();
            } 
        }

        /// <summary>
        /// 验证表单的值是否有效果
        /// </summary>
        /// <returns></returns>
        protected virtual bool Verifiy()
        {
            return VerifiyChildren(this); 
        }

        protected virtual bool Verifiy(DependencyObject reference)
        {
            return VerifiyChildren(reference);
        }

        private bool VerifiyChildren(DependencyObject reference)
        {
            
            int count = VisualTreeHelper.GetChildrenCount(reference);
            for (int i = 0; i < count; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(reference, i);
                if (child is IForm)
                {
                    IForm form = (IForm)child;
                    if (form.Required) //如果是必须项
                    {
                        bool verifiy = form.Verifiy();
                        if (!verifiy) //如果失败直接返回
                        {
                            return false;
                        }
                    }
                } 
                else
                {
                    if (child is ContentControl || child is TextBlock)
                    { 
                        continue;
                    }
                    else
                    {
                        return VerifiyChildren(child);
                    }
                   
                } 
            }
            return true;
        }
    }
}
